#include <kutils.h>
#include "gdt.h"
#include "display.h"

/* Defines a GDT entry. We say packed, because it prevents the
*  compiler from doing things that it thinks is best: Prevent
*  compiler "optimization" by packing */
struct gdt_entry
{
    u16int limit_low;
    u16int base_low;
    u8int base_middle;
    u8int access;
    u8int granularity;
    u8int base_high;
} __attribute__((packed));

/* Special pos32inter which includes the limit: The max bytes
*  taken up by the GDT, minus 1. Again, this NEEDS to be packed */
struct gdt_ptr
{
    u16int limit;
    u32int base;
} __attribute__((packed));

/* Our GDT, with 3 entries, and finally our special GDT pos32inter */
struct gdt_entry gdt[5];
struct gdt_ptr gp;

// in start.asm
extern void gdt_flush(void);

void gdt_set_gate(s32int num, u32int base, u32int limit, u8int access, u8int gran)
{
    /* Setup the descriptor base address */
    gdt[num].base_low = (u16int)(base & 0xFFFF);
    gdt[num].base_middle = (u8int)(base >> 16) & 0xFF;
    gdt[num].base_high = (u8int)(base >> 24) & 0xFF;

    /* Setup the descriptor limits */
    gdt[num].limit_low = (u16int)(limit & 0xFFFF);
    gdt[num].granularity = (u8int)((limit >> 16) & 0x0F);

    /* Finally, set up the granularity and access flags */
    gdt[num].granularity = (u8int)(gdt[num].granularity | (gran & 0xF0));
    gdt[num].access = access;
}

void gdt_install(void)
{
#ifdef FLUIDIUM_DEBUG
	write_string("GDT: Init\n");
#endif
    /* Setup the GDT pos32inter and limit */
    gp.limit = (sizeof(struct gdt_entry) * 5) - 1;
    gp.base = (u32int)&gdt;

    /* Our NULL descriptor */
    gdt_set_gate(0, 0, 0, 0, 0);

    /* The third entry is our pmode Code Segment. The base address
    *  is 0, the limit is 4GBytes, it uses 4KByte granularity,
    *  uses 32-bit opcodes, and is a Code Segment descriptor.
    *  Please check the table above in the tutorial in order
    *  to see exactly what each value means */
    gdt_set_gate(1, 0x00000000, 0xFFFFFFFF, 0x9A, 0xCF);

    /* The third entry is our pmode Data Segment. It's EXACTLY the
    *  same as our code segment, but the descriptor type in
    *  this entry's access byte says it's a Data Segment */
    gdt_set_gate(2, 0x00000000, 0xFFFFFFFF, 0x92, 0xCF);

	//a 16 bit code segment for use in the shutdown code
	 gdt_set_gate(3, 0x00000000, 0x0000FFFF, 0x9A, 0x80);

	//a 16 bit data segment for use in the shutdown code
	 gdt_set_gate(4, 0x00000000, 0x0000FFFF, 0x92, 0x80);

    /* Flush out the old GDT and install the new changes! */
    gdt_flush();
}
